﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Data;
using System.Drawing;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using QT.Windows.Shell;

namespace SiteMapService
{
    public partial class Form1 : GlassForm
    {
        #region Attributes

        private string ServiceName = "SiteMap";
        private string LogPath = Environment.CurrentDirectory + @"\logs";

        #endregion

        #region Form

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            InitForm();

            if (CheckService()) this.cbService.Checked = true;
            else this.cbService.Checked = false;
        }

        #endregion

        #region Event

        #region GlassButton

        private void gbtnSiteMapSave_Click(object sender, EventArgs e)
        {
            Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            appConfig.AppSettings.Settings["Time"].Value = this.dtpTime.Value.ToString("HH:mm:ss");
            appConfig.AppSettings.Settings["SitePath"].Value = this.tbSitepPath.Text;
            appConfig.AppSettings.Settings["SiteURIPath"].Value = this.tbSiteURIPath.Text;
            appConfig.AppSettings.Settings["SiteIndexPath"].Value = this.tbSiteIndexPath.Text;
            appConfig.AppSettings.Settings["LogPath"].Value = this.tbLogPath.Text;
            appConfig.AppSettings.Settings["XMLns"].Value = this.tbNameSpace.Text;
            appConfig.Save();

            if (!CheckService())
            {
                MessageBox.Show("保存完成");
                return;
            }

            ServiceController sc = new ServiceController(ServiceName);
            try
            {
                if (sc.Status != ServiceControllerStatus.Stopped) sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped);
                sc.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            MessageBox.Show("保存完成");
        }

        private void gbtnDataBaseSave_Click(object sender, EventArgs e)
        {
            #region 有效性检查

            if (this.tbServerID.Text.Length == 0)
            {
                MessageBox.Show("请输入服务器地址");
                return;
            }
            if (this.tbUserID.Text.Length == 0)
            {
                MessageBox.Show("请检查用户名密码是否已输入");
                return;
            }
            if (this.tbDataBase.Text.Length == 0)
            {
                MessageBox.Show("请输入数据库名称");
                return;
            }
            if (!this.rtbSql.Text.Contains("Frequency"))
            {
                MessageBox.Show("SQL语句未找到字段列名\"Frequency\"");
                return;
            }
            if (!this.rtbSql.Text.Contains("Priority"))
            {
                MessageBox.Show("SQL语句未找到字段列名\"Priority\"");
                return;
            }

            #endregion

            #region 保存设置

            Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            appConfig.AppSettings.Settings["ServerID"].Value = this.tbServerID.Text;
            if (this.tbPassword.Text.Length != 0)
            {
                appConfig.AppSettings.Settings["UserID"].Value = QT.Security.AESHelper.AESEncrypt(this.tbUserID.Text);
                appConfig.AppSettings.Settings["Password"].Value = QT.Security.AESHelper.AESEncrypt(this.tbPassword.Text);
            }
            appConfig.AppSettings.Settings["DataBase"].Value = this.tbDataBase.Text;
            appConfig.AppSettings.Settings["MySql"].Value = this.rtbSql.Text;
            appConfig.Save();

            #endregion

            #region 重启服务

            if (!CheckService())
            {
                MessageBox.Show("保存完成");
                return;
            }

            ServiceController sc = new ServiceController(ServiceName);
            try
            {
                if (sc.Status != ServiceControllerStatus.Stopped) sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped);
                sc.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            #endregion

            MessageBox.Show("保存完成");
        }

        #endregion

        #region CheckBox

        private void cbService_Click(object sender, EventArgs e)
        {
            if (this.cbService.Checked)
            {
                CreateService();
            }
            else
            {
                DeleteService();
            }
        }

        #endregion

        #region TextBox

        private void tbSitepPath_DoubleClick(object sender, EventArgs e)
        {
            SaveFileDialog mySaveFileDialog = new SaveFileDialog();
            mySaveFileDialog.ValidateNames = true;
            mySaveFileDialog.Filter = "站点地图文件(*.xml)|*.xml";
            mySaveFileDialog.FilterIndex = 1;
            mySaveFileDialog.DefaultExt = "xml";
            mySaveFileDialog.FileName = "Sitemap%Y%M%D.xml";
            mySaveFileDialog.AddExtension = true;
            if (mySaveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            this.tbSitepPath.Text = mySaveFileDialog.FileName;
        }

        private void tbSiteIndexPath_DoubleClick(object sender, EventArgs e)
        {
            SaveFileDialog mySaveFileDialog = new SaveFileDialog();
            mySaveFileDialog.ValidateNames = true;
            mySaveFileDialog.Filter = "站点地图索引文件(*.xml)|*.xml";
            mySaveFileDialog.FilterIndex = 1;
            mySaveFileDialog.DefaultExt = "xml";
            mySaveFileDialog.FileName = "SiteMap_Index.xml";
            mySaveFileDialog.AddExtension = true;
            if (mySaveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            this.tbSiteIndexPath.Text = mySaveFileDialog.FileName;
        }

        private void tbLogPath_DoubleClick(object sender, EventArgs e)
        {
            FolderBrowserDialog myFolderBrowserDialog = new FolderBrowserDialog();
            if (myFolderBrowserDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            this.tbLogPath.Text = myFolderBrowserDialog.SelectedPath;
        }

        #endregion

        #endregion

        #region Method

        #region Service

        /// <summary>
        /// 检查服务是否已存在
        /// </summary>
        /// <returns>bool</returns>
        private bool CheckService()
        {
            ServiceController[] sc = ServiceController.GetServices();

            foreach (ServiceController service in sc)
            {
                if (service.ServiceName.ToUpper() == ServiceName.ToUpper()) return true;
                service.Dispose();
            }

            sc = null;

            return false;
        }

        /// <summary>
        /// 创建服务
        /// </summary>
        /// <returns></returns>
        private bool CreateService()
        {
            if (CheckService())
            {
                MessageBox.Show("服务已存在");
                return false;
            }

            Process process = new Process();
            try
            {
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = "sc.exe";
                process.StartInfo.Arguments = " create " + ServiceName + " binPath= \"" + Application.ExecutablePath + " -service\" type= \"share\" type= \"interact\" obj= \"LocalSystem\" start= \"auto\"";
                process.StartInfo.UseShellExecute = false;
                process.Start();
                string Result = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                process.Close();
            }

            if (!CheckService())
            {
                MessageBox.Show("安装失败");
                return false;
            }

            ServiceController sc = new ServiceController(ServiceName);
            try
            {
                sc.Start();
                sc.WaitForStatus(ServiceControllerStatus.Running);
                MessageBox.Show("安装完成。服务状态:" + sc.Status.ToString());
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            catch (Exception)
            {
                MessageBox.Show("系统错误");
                return false;
            }
            finally
            {
                sc.Dispose();
            }

            return true;
        }

        /// <summary>
        /// 删除服务
        /// </summary>
        /// <returns></returns>
        private bool DeleteService()
        {
            if (!CheckService())
            {
                MessageBox.Show("服务不存在");
                return false;
            }

            ServiceController sc = new ServiceController(ServiceName);
            try
            {
                if (sc.Status != ServiceControllerStatus.Stopped) sc.Stop();
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            catch (Exception)
            {
                MessageBox.Show("系统错误");
                return false;
            }
            finally
            {
                sc.Dispose();
            }

            Process process = new Process();
            try
            {
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = "sc.exe";
                process.StartInfo.Arguments = " delete " + ServiceName;
                process.StartInfo.UseShellExecute = false;
                process.Start();
                string Result = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                process.Close();
            }

            if (CheckService())
            {
                MessageBox.Show("卸载失败");
                return false;
            }
            else
            {
                MessageBox.Show("卸载完成");
                return true;
            }
        }

        #endregion

        private void InitForm()
        {
            try
            {
                #region SiteMap

                string Time = ConfigurationManager.AppSettings["Time"];
                string SitePath = ConfigurationManager.AppSettings["SitePath"];
                string SiteURIPath = ConfigurationManager.AppSettings["SiteURIPath"];
                string SiteIndexPath = ConfigurationManager.AppSettings["SiteIndexPath"];
                string NameSpace = ConfigurationManager.AppSettings["XMLns"];
                LogPath = ConfigurationManager.AppSettings["LogPath"];

                if (!string.IsNullOrEmpty(Time)) this.dtpTime.Value = DateTime.Parse(Time);
                this.tbSitepPath.Text = SitePath;
                this.tbSiteURIPath.Text = SiteURIPath;
                this.tbSiteIndexPath.Text = SiteIndexPath;
                this.tbLogPath.Text = LogPath;
                this.tbNameSpace.Text = NameSpace;

                #endregion

                #region DataBase

                string ServerID = ConfigurationManager.AppSettings["ServerID"];
                string UserID = ConfigurationManager.AppSettings["UserID"];
                string DataBase = ConfigurationManager.AppSettings["DataBase"];
                string MySql = ConfigurationManager.AppSettings["MySql"];

                this.tbServerID.Text = ServerID;
                this.tbUserID.Text = QT.Security.AESHelper.AESDecrypt(UserID);
                this.tbDataBase.Text = DataBase;
                this.rtbSql.Text = MySql;

                #endregion
            }
            catch (Exception ex)
            {
                Tools.outLog(LogPath, ex.Message);
            }
        }

        #endregion
    }
}
